using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using Contoso.Workflow.Model;

namespace Contoso.Workflow.LocalService
{
    public class ExpenseService : IExpenseService
    {
        #region IExpenseService Members

        public event EventHandler<ExpenseEventArgs> ExpenseSave;
        public event EventHandler<ExpenseEventArgs> ExpenseApprove;
        public event EventHandler<ExpenseEventArgs> ExpenseReject;
        public event EventHandler<ExpenseEventArgs> ExpenseSendBack;

        #endregion

        public void RaiseSaveEvent(ExpenseData _expenseData)
        {
            if (ExpenseSave != null)
            {
                ExpenseEventArgs e = new ExpenseEventArgs(_expenseData.InstanceID, _expenseData);
                e.WaitForIdle = true;
                ExpenseSave(null, e);
                //ResetEventDictionaryClass.Get(_expenseData.InstanceID).WaitOne();
            }
        }

        public void RaiseApproveEvent(ExpenseData _expenseData)
        {
            if (ExpenseApprove != null)
            {
                ExpenseEventArgs e = new ExpenseEventArgs(_expenseData.InstanceID, _expenseData);
                e.WaitForIdle = true;
                ExpenseApprove(null, e);
//                ResetEventDictionaryClass.Get(_expenseData.InstanceID).WaitOne();

            }
        }

        public void RaiseRejectEvent(ExpenseData _expenseData)
        {
            if (ExpenseReject != null)
            {
                ExpenseEventArgs e = new ExpenseEventArgs(_expenseData.InstanceID, _expenseData);
                e.WaitForIdle = true;
                ExpenseReject(null, e);
                //ResetEventDictionaryClass.Get(_expenseData.InstanceID).WaitOne();

            }
        }

        public void RaiseSendBackEvent(ExpenseData _expenseData)
        {
            if (ExpenseSendBack != null)
            {
                ExpenseEventArgs e = new ExpenseEventArgs(_expenseData.InstanceID, _expenseData);
                e.WaitForIdle = true;
                ExpenseSendBack(null, e);
                //ResetEventDictionaryClass.Get(_expenseData.InstanceID).WaitOne();

            }
        }
    }

    public static class ResetEventDictionaryClass
    {
        private static Dictionary<Guid, AutoResetEvent> resetEventDictionary = new Dictionary<Guid, AutoResetEvent>();

        public static AutoResetEvent Get(Guid guid)
        {
            AutoResetEvent resetEvent = null;
            if (resetEventDictionary.TryGetValue(guid, out resetEvent) == true)
            {
                return resetEvent;
            }
            else
            {
                return null;
            }
        }

        public static void Add(Guid guid, AutoResetEvent resetEvent)
        {
            resetEventDictionary.Add(guid, resetEvent);
        }

    }
}
